package com.example.handler.overflow;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.handler.MainActivity;
import com.example.handler.R;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

public class Static_Handler extends AppCompatActivity {



    private static class MyStaticHandler extends Handler {
        // 定义弱引用实例
        private WeakReference<Static_Handler> mainActivityWeakReference;

        public MyStaticHandler(Static_Handler activity) {
            // 使用WeakReference弱引用持有Activity实例
            this.mainActivityWeakReference = new WeakReference<>(activity);
        }

        // 通过重写handlerMessage() 从而确定更新UI的操作
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.d("MyHandler", "1的消息");
                    break;
                case 2:
                    Log.d("MyHandler", " 收到线程2的消息");
                    break;
            }
            for (int i = 0; i < 50; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(i);
            }
        }
    }


    class CalThread extends Thread//计算质数
    {
        public MyStaticHandler mHandler;

        public void run() {
            Looper.prepare();// Looper.prepare()来给线程创建消息循环

            mHandler = new MyStaticHandler(Static_Handler.this);
            Looper.loop();//Looper.loop()来使消息循环起作用。
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        CalThread calThread = new CalThread();
        calThread.start();
        while ( calThread.mHandler==null);
        calThread.mHandler.sendEmptyMessage(1);
    }

}
